<?php

namespace App\Services;

use App\Commons\CommonConstant;
use App\Datalog\Events\UserFirstupEventLog;
use App\Datalog\Users\UserFirstupSet;
use App\Jobs\FirstupQueue;
use App\Models\Channels;
use App\Models\Firstups;
use App\Models\Users;
use YQ\YqExtend;

class FirstupService extends ServiceBase
{
    // 设备码是否有效
    public function validDeviceNum($device_num)
    {
        if ($device_num === '' || $device_num === 'null' || $device_num === 'undefined' || is_null($device_num)) {
            return false;
        }

        if (strpos($device_num, '00000000') === 0 || $device_num == '00-00-00') {
            return false;
        }

        return true;
    }

    // 根据设备类型获得可判断唯一设备id的字段
    public function getDeviceKeysByDeviceType($device_type)
    {
        if ($device_type == CommonConstant::DEVICE_TYPE_IOS) {
            $keys = ['idfv', 'idfa', 'device_num', 'click_id', 'openid'];
        } else if ($device_type == CommonConstant::DEVICE_TYPE_ANDROID) {
            $keys = ['android_id', 'oaid', 'google_adid', 'imei', 'device_num', 'click_id', 'openid'];
        } else {
            $keys = ['device_num', 'click_id', 'openid'];
        }

        return $keys;
    }

    public function firstup($params)
    {
        $game_id         = $params['game_id'];
        $channel         = $params['channel'];
        $game_channel_id = $params['game_channel_id'] ?? 0;
        $game_channel_id = GameChannelService::getInstance()->checkAndGetId($game_id, $channel, $game_channel_id);

        $device_type = $params['device_type'] ?? 0;
        $keys = $this->getDeviceKeysByDeviceType($device_type);

        $haskey      = false;
        $device_nums = [];
        $firstup     = null;
        foreach ($keys as $key) {
            if (!isset($params[$key]) || !$this->validDeviceNum($params[$key])) {
                continue;
            }
            $haskey            = true;
            $device_num        = $params[$key];
            $device_nums[$key] = $device_num;
            if (!$firstup) {
                $firstup = Firstups::whereRaw("game_id={$game_id} AND channel={$channel} AND {$key}='{$device_num}'")->first();
                // 此处不做break，需要循环完毕填充 device_nums, 为后续补充设备信息判断。
            }
        }

        if ($haskey !== true) {
            return false;
        }

        // 补齐不存在的设备信息
        if ($firstup) {
            foreach ($device_nums as $key => $val) {
                if (!$this->validDeviceNum($firstup->{$key})) {
                    $firstup->{$key} = $val;
                }
                $firstup->save();
            }

            return true;
        }

        // 将数据落地
        $firstup                  = new Firstups;
        $firstup->create_time     = time();
        $firstup->game_id         = $game_id;
        $firstup->channel         = $channel;
        $firstup->game_channel_id = $game_channel_id;
        $firstup->device_type     = $device_type;
        $firstup->package_id      = $params['package_id'];
        $firstup->click_id        = $params['click_id'] ?? '';
        $firstup->clue_token      = $params['clue_token'] ?? '';
        $firstup->ad_package_id   = $params['ad_package_id'] ?? '';
        $firstup->ip              = YqExtend::getIP();
        SdkService::getInstance()->supplementDevice($firstup, $params);
        $firstup->save();

        // 队列执行激活后的一系列事件
        FirstupQueue::dispatch($firstup->id, $params)->onQueue('default');

        return true;
    }

    // 匹配用户的激活
    public function searchFirstup($user)
    {
        $game_id     = $user->game_id;
        $channel     = $user->channel;
        $device_type = $user->device_type;
        $keys = $this->getDeviceKeysByDeviceType($device_type);

        // 允许注册比激活早半小时的误差
        $limit   = $user->create_time + 18000;
        $firstup = null;
        foreach ($keys as $key) {
            if (!isset($user[$key]) || !$this->validDeviceNum($user[$key])) {
                continue;
            }
            $device_num = $user[$key];
            $firstup    = Firstups::whereRaw("game_id={$game_id} AND channel={$channel} AND {$key}='{$device_num}'")->first();
            if (!$firstup || $firstup->create_time > $limit) {
                continue;
            }
            break;
        }

        return $firstup;
    }

    public function handleUserFirstup(Users $user)
    {
        if ($user->firstup_id > 0) {
            return;
        }

        $firstup = $this->searchFirstup($user);
        if (!$firstup) {
            return;
        }

        $user->firstup_id = $firstup->id;
        $user->save();

        // userset
        UserFirstupSet::getInstance()->addSet($user);

        // 如果是ios，并且账号有idfa而激活没有，则将账号idfa赋值给激活
        if ($user->idfa != $firstup->idfa && $user->device_type == CommonConstant::DEVICE_TYPE_IOS) {
            if (!$this->validDeviceNum($firstup->idfa)) {
                $firstup->idfa = $user->idfa;
                $firstup->save();
            }
        }

        // 如果是微信小游戏，则将小游戏的openid赋值给firstup，方便firstup进行匹配归因
        if ($user->channel == Channels::CHANNEL_WXGAME) {
            $firstup->openid = $user->channel_openid2;
            $firstup->save();
        }

        // 如果是8827wan渠道，则将小程序壳的openid赋值给firstup，方便firstup进行匹配归因
        if ($user->channel == Channels::CHANNEL_H5) {
            $firstup->openid = $user->channel_openid2;
            $firstup->save();
        }

        return true;
    }
}
